package com.hmsproject.common;

import java.net.Inet4Address;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.MessagingException;

import com.hmsproject.datastructures.Hotel;
import com.hmsproject.datastructures.User;
import com.hmsproject.datastructures.event.Event;
import com.hmsproject.datastructures.mail.HMSMail;
import com.hmsproject.datastructures.transactions.Transaction;
import com.hmsproject.datastructures.transactions.UserPreferences;
import com.hmsproject.db.inmemorydb.HMSInMemoryDBConnection;
import com.hmsproject.db.inmemorydb.HotelMap;
import com.hmsproject.db.inmemorydb.TransactionMap;
import com.hmsproject.db.inmemorydb.UserMap;
import com.hmsproject.db.util.HMSDBUtil;
import com.hmsproject.livedata.LiveDealCriterion;
import com.hmsproject.livedata.LiveDealData;

public class HMSUtil {
	
	private static HMSUtil hmsUtil = new HMSUtil();
	
	private String serverAddress = "localhost";
	
	private HMSUtil(){
		try{
			serverAddress = Inet4Address.getLocalHost().getHostAddress();
			//serverAddress = "localhost";
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static HMSUtil getInstance(){
		return hmsUtil;
	}	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		HMSUtil.getInstance().sendMail("satsrinister@gmail.com", 12345678);

	}
	
	public void sendMail(String toAddress, long verificationCode){
		
		String from = "hmsuser441@gmail.com";
	    String host = "smtp.gmail.com";
	    String port = "587";

	    Properties properties = System.getProperties();
	    properties.setProperty("mail.smtp.host", host);
	    properties.setProperty("mail.smtp.port", port);
	    properties.setProperty("mail.smtp.starttls.enable", "true");

	    Session session = Session.getDefaultInstance(properties);

	      try{
	         MimeMessage message = new MimeMessage(session);
	         message.setFrom(new InternetAddress(from));
	         message.addRecipient(Message.RecipientType.TO,
	                                  new InternetAddress(toAddress));

	         message.setSubject("HMS User Verification mail");
	         message.setText("Hello " + toAddress + ",\n\n Please verify yourself by clicking the following link.\n\n http:\\\\" + getServerAddress() + ":8080\\hms\\hmsrest\\verifyUser\\"+verificationCode 
	        		 	+ "\n\n\n Thank You \n HMS Admin");


	         Transport tr = session.getTransport("smtp");
	         tr.connect(host, "hmsuser441@gmail.com", "hmsuser123");
	         message.saveChanges();
	         tr.sendMessage(message, message.getAllRecipients());
	         tr.close();

	      }catch (MessagingException mex) {
	         mex.printStackTrace();
	      }
		
		
	}
	
	public void forgotPassword(String toAddress, String password){
		
		String from = "hmsuser441@gmail.com";
	    String host = "smtp.gmail.com";
	    String port = "587";

	    Properties properties = System.getProperties();
	    properties.setProperty("mail.smtp.host", host);
	    properties.setProperty("mail.smtp.port", port);
	    properties.setProperty("mail.smtp.starttls.enable", "true");

	    Session session = Session.getDefaultInstance(properties);

	      try{
	         MimeMessage message = new MimeMessage(session);
	         message.setFrom(new InternetAddress(from));
	         message.addRecipient(Message.RecipientType.TO,
	                                  new InternetAddress(toAddress));

	         message.setSubject("HMS Password recovery mail");
	         message.setText("Hello " + toAddress + ",\n\n Please find below your HMS user password.\n\n " + password 
	        		 	+ "\n\n\n Thank You \n HMS Admin");


	         Transport tr = session.getTransport("smtp");
	         tr.connect(host, "hmsuser441@gmail.com", "hmsuser123");
	         message.saveChanges();
	         tr.sendMessage(message, message.getAllRecipients());
	         tr.close();

	      }catch (MessagingException mex) {
	         mex.printStackTrace();
	      }
		
		
	}
	
	

	
	public LiveDealData buyDeal(LiveDealData liveDealData, String emailAdddress){
		
		LiveDealData freshLiveDealData = HMSInMemoryDBConnection.getInstance().getLiveDealData(liveDealData.getDeal().getDealId());
		
		List<LiveDealCriterion> liveDealCriterions = freshLiveDealData.getLiveDealCriterions();
		List<LiveDealCriterion> tobeRemovedLiveDealCriterions = new ArrayList<LiveDealCriterion>();
		int noOfRoomsBooked = liveDealData.getNoOfRooms();
		int additionalpercent = 0;
		for(int i = 0; i < liveDealCriterions.size(); i++){
			LiveDealCriterion currentLiveDealCriterion = liveDealCriterions.get(i);
			
			if(currentLiveDealCriterion.getNoOfRoomsMore() > noOfRoomsBooked){
				currentLiveDealCriterion.setNoOfRoomsMore(currentLiveDealCriterion.getNoOfRoomsMore() - noOfRoomsBooked);
				freshLiveDealData.setAfterDiscount(additionalpercent);
				break;
			}
			additionalpercent += currentLiveDealCriterion.getAdditionalPercentOff();
			tobeRemovedLiveDealCriterions.add(currentLiveDealCriterion);
			noOfRoomsBooked = noOfRoomsBooked - currentLiveDealCriterion.getNoOfRoomsMore();
		}
		
		liveDealCriterions.removeAll(tobeRemovedLiveDealCriterions);
		freshLiveDealData.setAlreadyBooked(freshLiveDealData.getAlreadyBooked() + liveDealData.getNoOfRooms());
		freshLiveDealData.setAfterDiscount(additionalpercent);
		
		int originalPrice = freshLiveDealData.getOriginalPrice();
		freshLiveDealData.setCurrentPrice(freshLiveDealData.getCurrentPrice() - originalPrice*additionalpercent/100);
		freshLiveDealData.setAvailableForBooking(freshLiveDealData.getAvailableForBooking() - liveDealData.getNoOfRooms());
		freshLiveDealData.setDeal(liveDealData.getDeal());
		freshLiveDealData.setNoOfRooms(liveDealData.getNoOfRooms());
		
		Transaction newTransacion = new Transaction(emailAdddress, liveDealData.getDeal(), new UserPreferences(liveDealData.getNoOfRooms()), new Date(),freshLiveDealData.getTotalCost());
		TransactionMap.getInstance().addTransaction(newTransacion);
		
		freshLiveDealData.setFromDate(liveDealData.getFromDate());
		freshLiveDealData.setToDate(liveDealData.getToDate());
		
		List<Transaction> transactionList = TransactionMap.getInstance().getTransactionListForDeal(liveDealData.getDeal().getDealId());
		

		
		try{
			new HotellieThread(newTransacion,freshLiveDealData, UserMap.getInstance().getUser(emailAdddress)).start();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return freshLiveDealData;
		
	}
	

	public LiveDealData fire(LiveDealData liveDealData){
		
		List<LiveDealCriterion> liveDealCriterions = liveDealData.getLiveDealCriterions();
		List<LiveDealCriterion> tobeRemovedLiveDealCriterions = new ArrayList<LiveDealCriterion>();
		int noOfRoomsBooked = liveDealData.getNoOfRooms();
		int additionalpercent = 0;
		for(int i = 0; i < liveDealCriterions.size(); i++){
			LiveDealCriterion currentLiveDealCriterion = liveDealCriterions.get(i);
			
			if(currentLiveDealCriterion.getNoOfRoomsMore() > noOfRoomsBooked){
				currentLiveDealCriterion.setNoOfRoomsMore(currentLiveDealCriterion.getNoOfRoomsMore() - noOfRoomsBooked);
				break;
			}
			additionalpercent += currentLiveDealCriterion.getAdditionalPercentOff();
			tobeRemovedLiveDealCriterions.add(currentLiveDealCriterion);
			noOfRoomsBooked = noOfRoomsBooked - currentLiveDealCriterion.getNoOfRoomsMore();
		}
		
		liveDealCriterions.removeAll(tobeRemovedLiveDealCriterions);
		liveDealData.setAlreadyBooked(liveDealData.getAlreadyBooked() + liveDealData.getNoOfRooms());
		
		int originalPrice = liveDealData.getOriginalPrice();
		liveDealData.setCurrentPrice(liveDealData.getCurrentPrice() - originalPrice*additionalpercent/100);
		
		return liveDealData;
		
	}
	
	

	public String getServerAddress(){
		return serverAddress;
	}

}
